package com.yywq.controller;


import com.yywq.error.BusinessException;
import com.yywq.error.EnumBusinessError;
import com.yywq.response.CommonReturnType;
import com.yywq.utils.MyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @author: 吴磊
 * @program: yywq
 * @create: 2021-03-18 18:46
 */

/**
 * 简单的说就是封装 异常  ，让异常显示在前端人性化
 */
@ControllerAdvice
public class BaseController {
    @Autowired
    private MyUtil myUtil;

    /**
     * 定义exceptionhandler解决未被controller层吸收的exception
     * 避免在前端页面抛出异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    private Object exceptionHandler(HttpServletRequest request, Exception e) throws BusinessException {
        HashMap<String, Object> responseData = new HashMap<>();
        if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            responseData.put("errorCode", businessException.getErrorCode());
            responseData.put("errorMsg", businessException.getErrorMsg());
        } else {
            responseData.put("errorCode", EnumBusinessError.UNKNOWN_ERROR.getErrorCode());
            responseData.put("errorMsg", EnumBusinessError.UNKNOWN_ERROR.getErrorMsg());
        }
        return CommonReturnType.create(responseData, "fail");
    }
}
